package com.eims.sls_app.ui;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.toolbox.RequestParams;
import com.eims.sls_app.dataaccess.utils.HttpUtils;
import com.eims.sls_app.protocol.RspBodyBaseBean;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.BaseHelper;
import com.eims.sls_app.view.MyToast;

import bls.juejin.cn.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class DocumentaryActivity extends MyBaseActivity implements OnClickListener {
	private static final String TAG = "DocumentaryActivity";
	private TextView documentary_tv_userName,documentary_tv_price,documentary_tv_PayAmount,documentary_tv_playTypeId;
	private EditText documentary_tv_Multiple;
	private TextView documentary_tv_ok;
	private TextView documentary_tv_maoshu;
	private ImageButton btn_back;
	private String name;
	private int cid;
	private int Price;
	private int money;
	private String playTypeId;
	private Context context;
	private String opt, auth, info, time, imei, crc; // 格式化后的参数
	private MyHandler mHandler;
	private MyAsynTask mMyAsynTask;
	private ProgressDialog pd;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_documentary);
		
		mHandler = new MyHandler();
		initView();
		inilist();
		 
	}
	

	private void inilist() {
		documentary_tv_ok.setOnClickListener(this);
		documentary_tv_Multiple.setSelection(documentary_tv_Multiple.getText().toString().length());
		documentary_tv_Multiple.addTextChangedListener(watcher);
		btn_back.setOnClickListener(this);
	}

	private void initView() {
		Intent intent = getIntent();
		name = intent.getStringExtra("name");
		cid = intent.getIntExtra("cid", 0);
		Price = intent.getIntExtra("Price", 0);
		playTypeId=intent.getStringExtra("playtypeid");
		btn_back = (ImageButton) findViewById(R.id.btn_back_doc);
		documentary_tv_userName = (TextView) findViewById(R.id.documentary_tv_userName2);
		documentary_tv_price = (TextView) findViewById(R.id.documentary_tv_price);
		documentary_tv_Multiple = (EditText) findViewById(R.id.documentary_tv_Multiple2);
		documentary_tv_PayAmount = (TextView)findViewById(R.id.documentary_tv_PayAmount2);
		documentary_tv_ok = (TextView) findViewById(R.id.documentary_tv_ok);
		documentary_tv_playTypeId=(TextView)findViewById(R.id.documentary_tv_playing);
		documentary_tv_maoshu=(TextView)findViewById(R.id.documentary_tv_playing_01);
		documentary_tv_userName.setText(name);
		documentary_tv_price.setText(Price+"");
		documentary_tv_PayAmount.setText(Price+"");
		if (playTypeId.startsWith("72")) {
			documentary_tv_playTypeId.setText("竞彩足球");
			documentary_tv_maoshu.setVisibility(View.GONE);
		}else {
			documentary_tv_playTypeId.setText("竞彩篮球");
			documentary_tv_maoshu.setVisibility(View.VISIBLE);
		}
		
		
	}
	private  long lastClickTime;

	public  boolean isFastDoubleClick() {
		long time = System.currentTimeMillis();
		long timeD = time - lastClickTime;
		if (0 < timeD && timeD < 10000) {
			return true;
		}
		lastClickTime = time;
		return false;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.documentary_tv_ok:
			double moneys = Double.parseDouble(money+"");
			int a = (new Double(moneys).compareTo(new Double(App.user.getBalance())+new Double(App.user.getHandselAmount())));
			if (a>0) {
				Intent intent_alipay = new Intent();
				Bundle bundle_alipay = new Bundle();
				intent_alipay.setClass(DocumentaryActivity.this,
						AmountOfCharge.class);
				bundle_alipay.putInt("Type", 1);
				intent_alipay.putExtras(bundle_alipay);
				startActivity(intent_alipay);
			}else if (App.user == null) {
				Intent intent;
				MyToast.getToast(DocumentaryActivity.this, "请先登陆").show();
				intent = new Intent(DocumentaryActivity.this, LoginActivity.class);
				intent.putExtra("loginType", "bet");
				DocumentaryActivity.this.startActivity(intent);
			}else  {
				
				if (isFastDoubleClick()) {
					Toast.makeText(DocumentaryActivity.this, "请不要在10秒内多次重复跟单！", Toast.LENGTH_SHORT).show();
				} else {
					if(moneys >= 50d) {
						documentary_tv_ok.setEnabled(false);
						pd = BaseHelper.showProgress(DocumentaryActivity.this, "", "出票中...", true, false);
						mMyAsynTask = new MyAsynTask();
						mMyAsynTask.execute();
					}else{
						Toast.makeText(DocumentaryActivity.this, "投注金额须大于50元！", Toast.LENGTH_LONG).show();
					}
				}
			}
			break;
		case R.id.btn_back_doc:
			finish();
			break;

		default:
			break;
		}
		
	}
	TextWatcher watcher = new TextWatcher() {
		
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			
			
		}
		
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			
			
		}
		
		@Override
		public void afterTextChanged(Editable s) {
			
			/*if (documentary_tv_Multiple.toString().trim().length() != 0) {
				if (Integer.parseInt(documentary_tv_Multiple.toString().trim()) > 99999) {
					
					MyToast.getToast(getApplicationContext(), "最大倍数为99999")
							.show();
					//documentary_tv_Multiple.setText("99999");
				} else if ("0".equals(documentary_tv_Multiple.getText().toString().trim())) {
					documentary_tv_Multiple.setText("1");
					
					//MyToast.getToast(getApplicationContext(), "最小为1倍").show();
				}
			}*/
			changeTextShow();
		}

		
	};
	/** 公用跳转方法 */
	private void ToOtherActivity(int lotteryType) {
		Intent intent = new Intent(DocumentaryActivity.this, MyAllLotteryActivity.class);
		intent.putExtra("index", lotteryType);
		this.startActivity(intent);

	}
	private void changeTextShow() {
		String multiple = documentary_tv_Multiple.getText() + "";
		if ("".equals(multiple)) {
			multiple = "1";
		}
		
		money = Price * Integer.parseInt(multiple);
		documentary_tv_PayAmount.setText(money+"");
		
	}
	
class MyAsynTask extends AsyncTask<Integer, Integer, String> {
		
		
		String error = "-1";

		@Override
		protected String doInBackground(Integer... params) {
			
				opt = "89";
				time = RspBodyBaseBean.getTime();
				imei = RspBodyBaseBean.getIMEI(context);
				String multiple = documentary_tv_Multiple.getText().toString();
				if (multiple.equals("")) {
					multiple = "1";
				}
				info = RspBodyBaseBean.change_cid(cid+"", multiple);
				
				// String key = MD5.md5(App.user.getUserPass() + App.MD5_key);
				String key = App.key;
				if (App.user==null) {
					crc = RspBodyBaseBean.getCrc(time, imei, key, info,
							"-1");
					auth = RspBodyBaseBean.getAuth(crc, time, imei, "-1");
				}else {
					crc = RspBodyBaseBean.getCrc(time, imei, key, info,
							App.user.getUid());
					auth = RspBodyBaseBean.getAuth(crc, time, imei, App.user.getUid());
				}
				
				String[] values = { opt, auth, info };
				Log.i(TAG, "跟单："+RequestParams.convertParams(DocumentaryActivity.this, opt, info));
				String result = HttpUtils.doPost(App.names, values,
						App.path);
				System.out.println("晒单：" + result);
				if (result.equals("重复晒单")) {
					return "1";
				}
				if (result.equals("该方案不能跟单")) {
					return "1";
				}
				try {
					JSONObject jsonObject = new JSONObject(result);
					error = jsonObject.optString("error");
					//error = "0";
				} catch (JSONException e) {
				
					e.printStackTrace();
				}
			
			return error;
		}

		@Override
		protected void onPostExecute(String result) {
			
			mHandler.sendEmptyMessage(Integer.parseInt(result));
			
			super.onPostExecute(result);
		}
	}

@SuppressLint("HandlerLeak")
class MyHandler extends Handler  {
	@Override
	public void handleMessage(Message msg) {
		documentary_tv_ok.setEnabled(true);
		if (pd!=null) {
			pd.dismiss();
		}
		switch (msg.what) {
		case 0:
			ToOtherActivity(0);
			finish();
			
			//MyToast.getToast(context, "跟单成功").show();
			
			break;
		case 1:
			Toast.makeText(DocumentaryActivity.this, "重复跟单", Toast.LENGTH_SHORT).show();
//			MyToast.getToast(context, "重复跟单").show();
			finish();
			break;
		case -111:
			//MyToast.getToast(context, "此单已截止").show();
			finish();
			break;
		case -134:
			Intent intent_alipay = new Intent();
			Bundle bundle_alipay = new Bundle();
			intent_alipay.setClass(DocumentaryActivity.this,
					AmountOfCharge.class);
			bundle_alipay.putInt("Type", 1);
			intent_alipay.putExtras(bundle_alipay);
			startActivity(intent_alipay);
			break;
		default:
			break;
		}
		super.handleMessage(msg);
	}
}


}


